import 'package:flutter/material.dart';

import '../extentions/datetime_extensions.dart';
import '../widgets/status_tag_widget.dart';
import 'exception_log_detail_page.dart';
import 'http_log_detail_page.dart';
import 'logger.dart';

class LogListPage extends StatefulWidget {
  final bool isFromRemote;

  const LogListPage({
    Key? key,
    this.isFromRemote = false,
  }) : super(key: key);

  @override
  _LogListPageState createState() => _LogListPageState();
}

class _LogListPageState extends State<LogListPage> {
  List<Log>? logs;

  static const text14_red =
      const TextStyle(color: const Color(0xFFF55C5E), fontSize: 14);

  static const text14_yellow =
      const TextStyle(color: const Color(0xFFFA8C16), fontSize: 14);

  static const text14_99 =
      const TextStyle(color: const Color(0xff999999), fontSize: 14);

  @override
  void initState() {
    super.initState();
    logs = widget.isFromRemote
        ? Logger.remoteLogs
        : Logger.getAll().reversed.toList();
  }

  @override
  Widget build(BuildContext context) {
    final textTheme = Theme.of(context).textTheme;
    return Scaffold(
      appBar: AppBar(
          title: Text(widget.isFromRemote ? '远程日志' : '日志列表'),
          centerTitle: true,
          actions: [
            if (!widget.isFromRemote)
              /*Logger.remoteLogs?.isNotEmpty == true
                  ? buildPopupMenuButton()
                  : */
              Builder(
                builder: (context) => InkWell(
                  onTap: () {
                    //_inputDialog();
                  },
                  child: Container(
                      alignment: Alignment.center,
                      padding: EdgeInsets.symmetric(horizontal: 15),
                      child: Text('获取日志')),
                ),
              ),
          ]),
      body: ListView.separated(
          itemBuilder: (context, index) {
            Log log = logs![index];
            if (log is HttpLog) {
              return _buildHttpItem(logs![index] as HttpLog, textTheme);
            } else if (log is ExceptionLog) {
              return _buildExceptionItem(log);
            } else {
              return _buildItem(log as NormalLog);
            }
          },
          separatorBuilder: (context, index) => Divider(height: 1),
          itemCount: logs!.length),
    );
  }

  Widget _buildExceptionItem(ExceptionLog log) {
    return InkWell(
      onTap: () {
        if (log.stack.isNotEmpty) {
          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
            return ExceptionLogDetailPage(log: log);
          }));
        }
      },
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 5),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(log.time?.format(timePatternYearMonthHourMinuteSecondSlash) ??
                ""),
            Text(log.exception,
                style: text14_red,
                maxLines: 3,
                overflow: TextOverflow.ellipsis),
          ],
        ),
      ),
    );
  }

  Widget _buildItem(NormalLog log) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 5),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(log.time?.format(timePatternYearMonthHourMinuteSecondSlash) ??
              ""),
          Text(log.message, style: text14_yellow),
        ],
      ),
    );
  }

  Widget _buildHttpItem(HttpLog log, TextTheme textTheme) {
    return InkWell(
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(builder: (context) {
          return HttpLogDetailPage(log: log);
        }));
      },
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (log.summary != null) ...[
              Row(
                children: [
                  Expanded(
                    child: Text(
                      log.summary!.title,
                      style: TextStyle(
                        color: getUrlColor(log.url),
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  StatusTagWidget(text: log.summary?.authorName ?? ""),
                ],
              ),
              Text(
                log.url!,
                style: TextStyle(
                  color: Colors.black54,
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
            Row(
              children: [
                Text(
                  log.statusCode.toString(),
                  style: log.isSuccess
                      ? const TextStyle(color: Color(0xFF2BB66B), fontSize: 14)
                      : const TextStyle(color: Color(0xFFF55C5E), fontSize: 14),
                ),
                SizedBox(width: 15),
                Expanded(
                  child: Text(log.time
                          ?.format(timePatternYearMonthHourMinuteSecondSlash) ??
                      ""),
                ),
                SizedBox(width: 30),
                Text('${log.totalTime}ms'),
              ],
            ),
            if (log.summary == null)
              Text(
                log.url!,
                style: TextStyle(
                  color: getUrlColor(log.url),
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
            if (log.params!.isNotEmpty)
              Text(log.params.toString(), style: text14_99)
          ],
        ),
      ),
    );
  }

  Color getUrlColor(String? url) {
    return Colors.primaries[url.hashCode % Colors.primaries.length];
  }

// PopupMenuButton<String> buildPopupMenuButton() {
//   return PopupMenuButton(
//     icon: Icon(Icons.more_horiz, color: Colors.white),
//     padding: EdgeInsets.zero,
//     offset: appBarPopupMenuOffset,
//     onSelected: (value) {
//       if (value == "view") {
//         Navigator.of(context).push(MaterialPageRoute(
//             builder: (context) => LogListPage(isFromRemote: true)));
//       } else if (value == "upload") {
//         _inputDialog();
//       }
//     },
//     itemBuilder: (BuildContext context) {
//       return [
//         PopupMenuItem<String>(
//           value: "view",
//           child: SizedBox(
//             width: popupMenuWidth2W,
//             child: Text("远程日志", style: popMenuStyle),
//           ),
//         ),
//         PopupMenuDivider(),
//         PopupMenuItem<String>(
//           value: "upload",
//           child: SizedBox(
//             width: popupMenuWidth2W,
//             child: Text("获取日志", style: popMenuStyle),
//           ),
//         )
//       ];
//     },
//   );
// }

/* void _inputDialog() {
    showInputDialog(context,
            titleText: '请输入用户手机号',
            keyboardType: TextInputType.number,
            inputFormatters: [TextFieldConstraint.onlyNumber],
            textAlign: TextAlign.start)
        .then((value) {
      if (!isEmpty(value)) {
        apis.pushCommandByMobile(
            value, jsonEncode(PushCommand.uploadLog(currentAccount.mobile)));
      }
    });
  }*/
}
